package com.alex.wechat.mp.menu.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.menu.entity.WxMenuEntity;
import com.alex.wechat.mp.menu.service.MenuTreeBuilder;
import com.alex.wechat.mp.menu.service.WxMenuServiceI;

import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

/**
 * 微信自定义菜单
 * 
 */
@Scope("prototype")
@Controller
@RequestMapping("/wxMenuController")
public class WxMenuController {
  private static final Logger logger = LoggerFactory.getLogger(WxMenuController.class);

  @Autowired
  private SystemService systemService;
  @Autowired
  private WxMenuServiceI wxMenuService;
  @Autowired
  private WxMpService wxMpService;
  @Autowired
  private MenuTreeBuilder menuTreeBuilder;

  @RequestMapping(params = "list")
  public ModelAndView list() {
    return new ModelAndView("com/gomore/wechat/mp/menu/menulist");
  }

  @RequestMapping(params = "getSubMenu")
  public void getSubMenu(HttpServletRequest request, HttpServletResponse response) {
    String accountid = WxContext.getOriginalId();
    String resMsg = "";
    JsonConfig config = new JsonConfig();
    config.setJsonPropertyFilter(new PropertyFilter() {
      public boolean apply(Object source, String name, Object value) {
        if (name.equals("menuList")) { // 要过滤的areas ，Map对象中的
          return true;
        } else {
          return false;
        }
      }
    });
    List<WxMenuEntity> textList = this.wxMenuService
        .findByHql("from WxMenuEntity t  where t.accountId = '" + accountid + "'");
    JSONArray json = JSONArray.fromObject(textList, config);
    resMsg = json.toString();

    try {
      response.setCharacterEncoding("utf-8");
      PrintWriter writer = response.getWriter();
      writer.write(resMsg);
      writer.flush();
      writer.close();
    } catch (IOException e) {
      logger.error("", e);
    }
  }

  @RequestMapping(params = "datagrid")
  @ResponseBody
  public List<TreeGrid> datagrid(TreeGrid treegrid, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    CriteriaQuery cq = new CriteriaQuery(WxMenuEntity.class);
    cq.eq("accountId", WxContext.getOriginalId());
    if (StringUtils.isNotBlank(treegrid.getId())) {
      cq.eq("parentId", treegrid.getId());
    }
    cq.addOrder("orders", SortDirection.asc);
    cq.add();

    List<WxMenuEntity> sourceMenus = systemService.getListByCriteriaQuery(cq, false);
    List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
    TreeGridModel treeGridModel = new TreeGridModel();
    treeGridModel.setTextField("name");
    treeGridModel.setParentText("url");
    treeGridModel.setOrder("orders");
    treeGridModel.setSrc("type");
    treeGridModel.setIdField("id");
    treeGridModel.setChildList("children");

    // 添加排序字段
    final List<WxMenuEntity> menuTree = menuTreeBuilder.buildTree(sourceMenus);
    treeGrids = systemService.treegrid(menuTree, treeGridModel);
    return treeGrids;
  }

  /**
   * 显示编辑或新增界面。
   * 
   * @param menuEntity
   * @param req
   * @return
   */
  @RequestMapping(params = "edit")
  public ModelAndView goEditView(WxMenuEntity menuEntity, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(menuEntity.getId())) {
      menuEntity = this.systemService.getEntity(WxMenuEntity.class, menuEntity.getId());
      if (StringUtils.isNotBlank(menuEntity.getParentId())) {
        WxMenuEntity parent = wxMenuService.get(WxMenuEntity.class, menuEntity.getParentId());
        req.setAttribute("fatherId", parent.getId());
        req.setAttribute("fatherName", parent.getName());
      }

      req.setAttribute("name", menuEntity.getName());
      req.setAttribute("type", menuEntity.getType());
      req.setAttribute("menuKey", menuEntity.getMenuKey());
      req.setAttribute("url", menuEntity.getUrl());
      req.setAttribute("orders", menuEntity.getOrders());
      req.setAttribute("menuEntity", menuEntity);
    }

    String fatherId = req.getParameter("fatherId");
    if (StringUtil.isNotEmpty(fatherId)) {
      WxMenuEntity fatherMenuEntity = this.systemService.getEntity(WxMenuEntity.class, fatherId);
      req.setAttribute("fatherId", fatherId);
      req.setAttribute("fatherName", fatherMenuEntity.getName());
    }

    return new ModelAndView("com/gomore/wechat/mp/menu/menuinfo");
  }

  /**
   * 保存菜单。
   * 
   * @param menuEntity
   * @param req
   * @param fatherName
   * @return
   */
  @RequestMapping(params = "save")
  @ResponseBody
  public AjaxJson save(WxMenuEntity menuEntity, HttpServletRequest req, String fatherName) {
    AjaxJson j = new AjaxJson();

    String message = null;
    if (StringUtil.isNotEmpty(menuEntity.getId())) {
      WxMenuEntity oldMenu = this.systemService.getEntity(WxMenuEntity.class, menuEntity.getId());

      WxMenuEntity menuTemp = new WxMenuEntity();
      if (oConvertUtils.isNotEmpty(fatherName)) {
        menuTemp.setId(fatherName);
      }
      oldMenu.setParentId(menuTemp.getId());

      try {
        MyBeanUtils.copyBeanNotNull2Bean(menuEntity, oldMenu);
        this.wxMenuService.saveOrUpdate(oldMenu);
        message = "更新" + oldMenu.getName() + "的菜单信息信息成功！";
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
      } catch (Exception e) {
        logger.error("", e);
        message = "更新" + oldMenu.getName() + "的菜单失败: " + e.getMessage();
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
      }

    } else {
      message = "添加" + menuEntity.getName() + "的信息成功！";
      // String fatherId = req.getParameter("fatherId");
      if (StringUtil.isNotEmpty(fatherName)) {
        WxMenuEntity tempMenu = this.systemService.getEntity(WxMenuEntity.class, fatherName);
        menuEntity.setParentId(tempMenu.getId());
      }

      if (WxContext.hasWxAccount()) {
        this.wxMenuService.save(menuEntity);
      } else {
        j.setSuccess(false);
        j.setMsg("请添加一个公众帐号。");
      }
      systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
    }
    return j;
  }

  @RequestMapping(params = "jumpselect")
  public ModelAndView jumpselect() {
    return new ModelAndView("");
  }

  @RequestMapping(params = "del")
  @ResponseBody
  public AjaxJson del(WxMenuEntity menuEntity, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    menuEntity = this.systemService.getEntity(WxMenuEntity.class, menuEntity.getId());

    this.systemService.delete(menuEntity);

    String message = "删除" + menuEntity.getName() + "菜单信息数据";
    systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params = "syncMenu")
  @ResponseBody
  public AjaxJson syncMenu(WxMenuEntity menuEntity, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();

    String message = null;
    WxMenu wxMenu = wxMenuService.buildWxMenu();
    try {
      wxMpService.getMenuService().menuCreate(wxMenu);
      message = "同步菜单信息数据成功！";
      j.setSuccess(true);
    } catch (WxErrorException e) {
      message = "同步菜单信息数据失败！错误码为：" + e.getError().getErrorCode() + "错误信息为："
          + e.getError().getErrorMsg();
      j.setSuccess(false);
    } finally {
      systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
      j.setMsg(message);
    }
    return j;
  }

  @RequestMapping(params = "treeMenu")
  @ResponseBody
  public List<TreeGrid> treeMenu(HttpServletRequest request, ComboTree comboTree) {
    boolean showChildren = "true".equals(request.getParameter("showChildren"));
    CriteriaQuery cq = new CriteriaQuery(WxMenuEntity.class);
    if (StringUtil.isNotEmpty(comboTree.getId())) {
      cq.eq("parentId", comboTree.getId());
    } else {
      cq.isNull("parentId");
    }
    cq.eq("accountId", WxContext.getOriginalId());
    cq.add();
    List<WxMenuEntity> menuList = wxMenuService.getListByCriteriaQuery(cq, false);

    List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
    TreeGridModel treeGridModel = new TreeGridModel();
    treeGridModel.setTextField("name");
    treeGridModel.setParentText("parent_name");
    treeGridModel.setParentId("parentId");
    treeGridModel.setSrc("url");
    treeGridModel.setIdField("id");
    treeGridModel.setChildList(showChildren ? "children" : "null");
    treeGrids = systemService.treegrid(menuList, treeGridModel);
    return treeGrids;
  }

}